package cn.stylefeng.guns.modular.api;

import cn.hutool.core.util.XmlUtil;
import cn.stylefeng.guns.core.RecoverConst;
import cn.stylefeng.guns.modular.business.common.CheckUtil;
import cn.stylefeng.guns.modular.business.common.MessageUtil;
import cn.stylefeng.guns.modular.business.common.TokenSingleton;
import cn.stylefeng.guns.modular.business.model.params.MessageDTO;
import cn.stylefeng.guns.modular.business.service.AccountService;
import cn.stylefeng.guns.modular.business.service.MessageService;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.core.util.StringUtils;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.wxpay.XmlHelper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import weixin.popular.api.UserAPI;
import weixin.popular.util.SignatureUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/gunsApi/")
@Slf4j
public class WxMessageApi extends BaseController {

    @Autowired
    MessageService messageService;

    @Autowired
    AccountService accountService;

    @ApiOperation("发送微信模板消息")
    @PostMapping("/wxMessage/send")
    public ResponseData send(@RequestBody MessageDTO messageDTO) {
        messageService.sendTemplateMessage(messageDTO);
        return ResponseData.success();
    }

    @ApiOperation("接收微信事件消息")
    @RequestMapping("/wx")
    public void wx(HttpServletRequest request, HttpServletResponse response) throws IOException {

        log.info("开始校验信息是否是从微信服务器发出");
        boolean ispost = Objects.equals("POST", request.getMethod().toUpperCase());
        if (ispost) {
            String message = "";
            log.debug("接入成功，正在处理逻辑");
            InputStream inputStream = request.getInputStream();
            Map<String, String> params = XmlHelper.of(inputStream).toMap();
            String toUserName = params.get("ToUserName");
            String fromUserName = params.get("FromUserName");
            String msgType = params.get("MsgType");
            String eventType = params.get("Event");
            log.info("事件参数，" + JSONObject.toJSONString(params));
            //判断请求是否事件类型 event
            if(MessageUtil.MESSAGE_EVENT.equals(msgType)){
                //若是关注事件  subscribe
                if(MessageUtil.EVENT_SUB.equals(eventType)){
                    String eventKey = params.get("EventKey");
                    log.info("EventKey：" + eventKey);
                    if (StringUtils.isNotEmpty(eventKey)) {
                        String[] refeeUsers = eventKey.split("_");
                        if (refeeUsers != null) {
                            // 判断账号是否重复
                            Integer count = accountService.count(new QueryWrapper<User>().eq("openid", toUserName));
                            if (count <= 0) {
                                weixin.popular.bean.user.User user = UserAPI.userInfo(TokenSingleton.getTokenSingleton().getWeixinToken(), fromUserName);
                                if (user != null) {
                                    //1、写入数据库，建立推荐关系
                                    //accountService.wxReg(toUserName, user.getNickname(), user.getSex(), user.getHeadimgurl(), Long.valueOf(refeeUsers[1]));
                                }
                            }
                        }
                    }
                    String mycontent = MessageUtil.menuText();
                    message = MessageUtil.initText(toUserName, fromUserName, mycontent);
                }
            }
            response.getWriter().print(message);
        } else {
            // 签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
                // 随机字符串
                String echostr = request.getParameter("echostr");
                log.debug("接入成功，echostr {}", echostr);
                response.getWriter().write(echostr);
            }
        }
    }

}


